<template>
  <div class="bandwidth-trend-panel">
    <!-- 顶部说明 -->
    <div class="top-bar">
      <span class="title">跑量带宽限速：</span>
      <el-tooltip content="带宽限速说明" placement="top">
        <i class="el-icon-question"></i>
      </el-tooltip>
      <span class="not-set">{{ speedVal }}</span>
      <el-link
        type="primary"
        style="margin-left: 8px"
        @click="openSpeedLimitSetting"
        >设置限速</el-link
      >
      <span class="flex-spacer"></span>
      <span class="grain">时间粒度 5min</span>
    </div>

    <el-drawer
      v-model="openSpeed"
      title="跑量限速设置"
      direction="rtl"
      :destroy-on-close="true"
    >
      <div class="speed-limit-setting">
        <!-- 顶部提示 -->
        <el-alert class="top-alert" type="warning" show-icon :closable="false">
          <template #title>
            <div>
              <b>须知：</b>
              <span>设置设备跑量限速，可能会导致利用率降低，请谨慎设置！</span>
            </div>
          </template>
        </el-alert>

        <el-form
          :model="form"
          :rules="rules"
          ref="formRef"
          label-width="100px"
          class="limit-form"
        >
          <el-form-item label="限速方式">
            <el-radio-group v-model="form.mode">
              <el-radio value="absolute">按带宽固定值限速</el-radio>
              <el-radio value="relative">按压测带宽比例限速</el-radio>
              <el-radio value="">不设置限速</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            label="限速单位"
            prop="value"
            v-if="
              form.isEnabled === 1 ||
              form.mode === 'absolute' ||
              form.mode === 'relative'
            "
          >
            <el-input-number
              v-model.number="form.value"
              :placeholder="placeholder"
              style="width: 220px"
              min="1"
              :max="maxNumber"
              type="number"
            >
              <template #suffix>
                <span>Mbps</span>
              </template>
            </el-input-number>
          </el-form-item>

          <div class="tip-row" v-if="form.mode === 'absolute'">
            <span class="tip-text">*设置后上行跑量将不会超过限速值</span>
          </div>
          <div class="tip-row" v-if="form.mode === 'relative'">
            <span class="tip-text"
              >*设置后请关注设备是否有压测带宽，以保证限速正常生效</span
            >
          </div>

          <el-form-item>
            <el-button type="primary" @click="onSubmit" :loading="loading"
              >确认</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>

    <div class="header-section">
      <div class="section-title-left">
        <div class="section-title">设备在线点数</div>
      </div>
      <!-- <div class="section-title-right">
        <el-date-picker
          v-model="deviceOnlineDateRange"
          type="date"
          value-format="YYYY-MM-DD HH:mm:ss"
          @change="handleDeviceOnlineDateChange"
        ></el-date-picker>
      </div> -->
    </div>
    <div ref="deviceOnlineChartRef" class="trend-chart"></div>

    <!-- 日期切换 -->
    <div class="header-section">
      <div class="section-title-left">
        <div class="section-title">上下行带宽</div>
      </div>
      <div class="section-title-right">
        <el-date-picker
          v-model="dateRange"
          type="date"
          value-format="YYYY-MM-DD HH:mm:ss"
          @change="handleDateChange"
        ></el-date-picker>
      </div>
    </div>
    <div ref="chartRef" class="trend-chart"></div>
    <!-- 下行带宽 -->
    <!-- <div class="section-title" style="margin-top: 32px">下行带宽</div> -->
    <!-- <div ref="downChartRef" class="trend-chart"></div> -->
  </div>
</template>

<script setup name="BandwidthTrendPanel">
import {
  ref,
  onMounted,
  onBeforeUnmount,
  nextTick,
  computed,
  getCurrentInstance,
  reactive,
  toRefs,
  watch,
} from "vue";
import * as echarts from "echarts";
import { ElMessage } from "element-plus";
import {
  bandwidthTrend,
  getDeviceLimitSpeed,
  updateDeviceLimitSpeed,
  getDeviceDetail,
  timeCountList,
} from "@/api/producer/device";

const props = defineProps({
  formDrawer: {
    type: Object,
    required: true,
  },
  activeName: { type: String, required: true },
});
const { proxy } = getCurrentInstance();
const dateRange = ref([]);

const deviceOnlineChartRef = ref(null);
let deviceOnlineChartInstance = null;
const deviceOnlineDateRange = ref([]);
const deviceOnlineData = ref([]);
const deviceOnlineTimeArr = ref([]);
const deviceOnlineMaxVal = ref(0);

const chartRef = ref(null);
let chartInstance = null;

const placeholder = ref("");
const maxNumber = ref(0);

// 生成时间点
const timeArr = ref([]);

// 上行带宽数据
const upData = ref([]);
const maxVal = ref(0);
// 下行带宽数据
const downData = ref([]);

const openSpeed = ref(false);
const speedVal = ref(0);
const loading = ref(false);

const option = {
  grid: { left: 60, right: 40, top: 40, bottom: 40 },
  tooltip: { trigger: "axis" },
  legend: { data: ["上行带宽", "下行带宽"], top: 5, right: 0 },
  xAxis: {
    type: "category",
    data: timeArr.value || [],
    axisLabel: { color: "#888" },
  },
  yAxis: {
    type: "value",
    min: 0,
    max: maxVal.value,
    axisLabel: { color: "#888" },
    name: "带宽 (Mbps)",
    nameTextStyle: { align: "center", padding: [0, 0, 0, 0] },
  },
  series: [
    {
      name: "上行带宽",
      type: "line",
      data: upData.value || [],
      showSymbol: false,
      smooth: true,
      lineStyle: { color: "#5B8FF9", width: 2 },
      areaStyle: { opacity: 0 },
    },
    {
      name: "下行带宽",
      type: "line",
      data: downData.value || [],
      showSymbol: false,
      smooth: true,
      lineStyle: { color: "#34c7be", width: 2 },
      areaStyle: { opacity: 0 },
    },
  ],
};

const deviceOnlineOption = {
  grid: { left: 60, right: 40, top: 40, bottom: 40 },
  tooltip: { trigger: "axis" },
  legend: { data: ["在线点数"], top: 5, right: 0 },
  xAxis: {
    type: "category",
    data: deviceOnlineTimeArr.value || [],
    axisLabel: { color: "#888" },
  },
  yAxis: {
    type: "value",
    min: 0,
    max: deviceOnlineMaxVal.value,
    axisLabel: { color: "#888" },
    name: "在线点数",
    nameTextStyle: { align: "center", padding: [0, 0, 0, 0] },
  },
  series: [
    {
      name: "在线点数",
      type: "line",
      data: deviceOnlineData.value || [],
      showSymbol: false,
      smooth: true,
      lineStyle: { color: "#5B8FF9", width: 2 },
      areaStyle: { opacity: 0 },
    },
  ],
};

const data = reactive({
  form: {},
  rules: {
    value: [
      { required: true, message: "请输入限速值", trigger: "blur" },
      { type: "number", message: "限速值必须为数字值", trigger: "blur" },
    ],
  },
  speedSetting: {},
});

const { form, rules, speedSetting } = toRefs(data);

watch([() => form.value.mode], ([newType, newValue]) => {
  console.log("limitType or limitValue changed:", newType, newValue);
  let num = null;
  if (newType === "absolute") {
    placeholder.value = "请输入1-10000";
    maxNumber.value = 10000;
  } else if (newType === "relative") {
    placeholder.value = "请输入1-99";
    maxNumber.value = 99;
  } else {
    maxNumber.value = 1;
    form.value.isEnabled = 2;
  }
});

// 提交表单
function onSubmit() {
  loading.value = true;
  let params = {};
  // 校验最大值
  if (form.value.mode === "absolute" && form.value.value > 10000) {
    ElMessage.warning("限速值不能超过10000");
    form.value.value = 10000;
    return;
  }
  if (form.value.mode === "relative" && form.value.value > 99) {
    ElMessage.warning("限速值不能超过99");
    form.value.value = 99;
    return;
  }
  if (form.value.mode == "") {
    form.value.isEnabled = 2;
  } else {
    form.value.isEnabled = 1;
  }

  if (form.value.isEnabled === 2) {
    Object.assign(params, {
      sn: form.value.sn,
      isEnabled: form.value.isEnabled,
      mode: speedSetting.value.mode,
      value: speedSetting.value.value,
    });
  } else {
    Object.assign(params, {
      sn: form.value.sn,
      isEnabled: form.value.isEnabled,
      mode: form.value.mode,
      value: form.value.value,
    });
  }

  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      updateDeviceLimitSpeed(params).then((res) => {
        ElMessage.success("提交成功");
        openSpeed.value = false;
        fetchData();
        loading.value = false;
      });
    }
  });
}

function initCharts() {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value);
    chartInstance.setOption(option);
    window.addEventListener("resize", resizeChart);
  }
}

function initDeviceOnlineCharts() {
  if (deviceOnlineChartRef.value) {
    deviceOnlineChartInstance = echarts.init(deviceOnlineChartRef.value);
    deviceOnlineChartInstance.setOption(deviceOnlineOption);
    window.addEventListener("resize", resizeDeviceOnlineChart);
  }
}

function disposeCharts() {
  window.removeEventListener("resize", resizeChart);
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
}

function disposeDeviceOnlineCharts() {
  window.removeEventListener("resize", resizeDeviceOnlineChart);
  if (deviceOnlineChartInstance) {
    deviceOnlineChartInstance.dispose();
    deviceOnlineChartInstance = null;
  }
}

function resizeChart() {
  chartInstance && chartInstance.resize();
}

function resizeDeviceOnlineChart() {
  deviceOnlineChartInstance && deviceOnlineChartInstance.resize();
}

function getTodayStart() {
  const date = new Date();
  date.setHours(0, 0, 0, 0);
  return date;
}

function getTodayEnd() {
  const date = new Date();
  date.setHours(23, 59, 59, 999);
  return date;
}

// pickerOptions (禁用未来的日期)
const pickerOptions = reactive({
  disabledDate: (time) => {
    return time.getTime() > Date.now();
  },
});

// 日期范围改变
function handleDateChange(val) {
  console.log(val);

  if (val) {
    dateRange.value = val;
  } else {
    // 如果清空，则默认今天
    setDefaultDateRange();
  }
}

// 设置默认日期范围为今天
function setDefaultDeviceOnlineDateRange() {
  const start = getTodayStart();
  const end = getTodayEnd();
  deviceOnlineDateRange.value = proxy.parseTime(start, "{y}-{m}-{d} {h}:{i}:{s}");
}

// 日期范围改变
function handleDeviceOnlineDateChange(val) {
  console.log(val);

  if (val) {
    deviceOnlineDateRange.value = val;
  } else {
    // 如果清空，则默认今天
    setDefaultDeviceOnlineDateRange();
  }
}

// 设置默认日期范围为今天
function setDefaultDateRange() {
  const start = getTodayStart();
  const end = getTodayEnd();
  dateRange.value = proxy.parseTime(start, "{y}-{m}-{d} {h}:{i}:{s}");
  deviceOnlineDateRange.value = proxy.parseTime(start, "{y}-{m}-{d} {h}:{i}:{s}");
}

onMounted(() => {
  setDefaultDateRange();
  setDefaultDeviceOnlineDateRange();
  nextTick(() => {
    initCharts();
    initDeviceOnlineCharts();
    fetchData();
  });
});
onBeforeUnmount(() => {
  disposeCharts();
  disposeDeviceOnlineCharts();
});

watch(
  [() => props.activeName, () => props.formDrawer.sn, () => dateRange.value],
  ([tab, sn, dateRangeVal], [oldTab, oldSn, oldDateRange]) => {
    if (tab === "second" && sn && dateRangeVal) {
      getBandwidthTrendData(sn);
    }
  },
  { immediate: true }
);

watch(
  [() => props.activeName, () => props.formDrawer.sn, () => deviceOnlineDateRange.value],
  ([tab, sn, dateRangeVal], [oldTab, oldSn, oldDateRange]) => {
    if (tab === "second" && sn && dateRangeVal) {
      getDeviceOnlineData(sn);
    }
  },
  { immediate: true }
);

// 获取设备在线点数数据
function getDeviceOnlineData(sn) {
  const params = { sn};
  timeCountList(params).then((res) => {
    if (res.code === 200) {
      if (res.data.length > 0) {
        deviceOnlineTimeArr.value = res.data.map((item) => item.time);
        deviceOnlineData.value = res.data.map((item) => item.count);

        let maxCount = Math.max(...deviceOnlineData.value);
        if (maxCount == 0) {
          deviceOnlineMaxVal.value = 5;
        } else {
          deviceOnlineMaxVal.value = Math.ceil(maxCount);
        }
        renderDeviceOnlineChart();
      } else {
        deviceOnlineTimeArr.value = [];
        deviceOnlineData.value = [];
        renderDeviceOnlineChart();
      }
    }
  });
}

// 获取带宽趋势数据
function getBandwidthTrendData(sn) {
     
  const params = { sn, timeId: dateRange.value };
  bandwidthTrend(params).then((res) => {
    if (res.code === 200) {
      if (res.rows.length > 0) {
        const data = res.rows;

        data.forEach((row) => {
          let downBandWidth = JSON.parse(row.downBandWidth);
          let upBandWidth = JSON.parse(row.upBandWidth);

          timeArr.value = downBandWidth.map((item) => item.time);
          downData.value = downBandWidth.map((item) => item.downBandWidth);
          upData.value = upBandWidth.map((item) => item.upBandWidth);

          let maxCombined = Math.max(...downData.value, ...upData.value);
          if (maxCombined == 0) {
            maxVal.value = 5;
          } else {
            maxVal.value = Math.ceil(maxCombined);
          }
        });
        renderChart();
      } else {
        timeArr.value = [];
        upData.value = [];
        downData.value = [];
        renderChart();
      }
    }
  });
}

function renderChart() {

  if (!chartInstance && chartRef.value) {
    chartInstance = echarts.init(chartRef.value);
  }
  if (chartInstance) {
    chartInstance.setOption({
      grid: { left: 60, right: 40, top: 40, bottom: 40 },
      tooltip: { trigger: "axis" },
      legend: { data: ["上行带宽", "下行带宽"], top: 5, right: 0 },
      xAxis: {
        type: "category",
        data: timeArr.value || [],
        axisLabel: { color: "#888" },
      },
      yAxis: {
        type: "value",
        min: 0,
        max: maxVal.value,
        axisLabel: { color: "#888" },
        name: "带宽 (Mbps)",
        nameTextStyle: { align: "center", padding: [0, 0, 0, 0] },
      },
      series: [
        {
          name: "上行带宽",
          type: "line",
          data: upData.value || [],
          showSymbol: false,
          smooth: true,
          lineStyle: { color: "#5B8FF9", width: 2 },
          areaStyle: { opacity: 0 },
        },
        {
          name: "下行带宽",
          type: "line",
          data: downData.value || [],
          showSymbol: false,
          smooth: true,
          lineStyle: { color: "#34c7be", width: 2 },
          areaStyle: { opacity: 0 },
        },
      ],
    });
  }
}

function renderDeviceOnlineChart() {
  if (!deviceOnlineChartInstance && deviceOnlineChartRef.value) {
    deviceOnlineChartInstance = echarts.init(deviceOnlineChartRef.value);
  }
  if (deviceOnlineChartInstance) {
    deviceOnlineChartInstance.setOption({
      grid: { left: 60, right: 40, top: 40, bottom: 40 },
      tooltip: { trigger: "axis" },
      legend: { data: ["在线点数"], top: 5, right: 0 },
      xAxis: {
        type: "category",
        data: deviceOnlineTimeArr.value || [],
        axisLabel: { color: "#888" },
      },
      yAxis: {
        type: "value",
        min: 0,
        max: deviceOnlineMaxVal.value,
        axisLabel: { color: "#888" },
        name: "在线点数",
        nameTextStyle: { align: "center", padding: [0, 0, 0, 0] },
      },
      series: [
        {
          name: "在线点数",
          type: "line",
          data: deviceOnlineData.value || [],
          showSymbol: false,
          smooth: true,
          lineStyle: { color: "#5B8FF9", width: 2 },
          areaStyle: { opacity: 0 },
        },
      ],
    });
  }
}

// 查询限速
function fetchData() {
  let params = { sn: props.formDrawer.sn };
  getDeviceLimitSpeed(params).then((res) => {
    form.value.sn = props.formDrawer.sn;

    if (res.data) {
      speedSetting.value = res.data;
      form.value.isEnabled = res.data.isEnabled;
      // form.value.mode = res.data.mode;
      form.value.value = res.data.value;
      if (res.data.isEnabled === 1) {
        if (res.data.mode === "absolute") {
          speedVal.value = `${res.data.value}MB`;
        } else if (res.data.mode === "relative") {
          speedVal.value = `${res.data.value}%`;
        }
      } else {
        speedVal.value = "不设置限速";
        form.value.mode = "";
      }
    } else {
      speedVal.value = "未设置";
      form.value.mode = "";
    }
  });
  if (props.activeName === "second") {
    getDeviceOnlineData(props.formDrawer.sn);
  }
}

// 打开限速设置
function openSpeedLimitSetting() {
  openSpeed.value = true;
}

// 关闭限速设置
function handleCloseSpeedSetting() {
  openSpeed.value = false;
}

// 修改限速
function updateSpeedLimit() {
  updateDeviceLimitSpeed(form.value).then((res) => {});
}

// 关闭
function handleClose() {}

// 内存释放
function releaseMemory() {
  timeArr.value = [];
  upData.value = [];
  downData.value = [];
  deviceOnlineData.value = [];
  deviceOnlineTimeArr.value = [];
  renderChart();
  renderDeviceOnlineChart();
}

function closeDialog() {
  // 清空所有数据
  form.value = {};
  upData.value = [];
  downData.value = [];
  timeArr.value = [];
  deviceOnlineData.value = [];
  deviceOnlineTimeArr.value = [];
  speedVal.value = 0;
  // 销毁图表
  disposeCharts();
  disposeDeviceOnlineCharts();
}
</script>

<style scoped>
.bandwidth-trend-panel {
  background: #fff;
  padding: 0;
}

.top-bar {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  margin-top: 8px;
}

.title {
  font-weight: bold;
  font-size: 16px;
}

.not-set {
  color: #888;
  margin-left: 4px;
  margin-right: 8px;
}

.flex-spacer {
  flex: 1;
}

.grain {
  color: #888;
}

.date-bar {
  margin-bottom: 8px;
}

.section-title {
  font-weight: normal;
  font-size: 15px;
  margin: 16px 0 8px 0;
}

.trend-chart {
  width: 100%;
  height: 400px;
  margin-bottom: 0;
}
.speed-limit-setting {
  padding: 16px 8px 0 8px;
  background: #fff;
  min-width: 400px;
}
.top-alert {
  margin-bottom: 24px;
  border-radius: 4px;
  border: 1px solid #ffe58f;
  background: #fffbe6;
  color: #ad8b00;
  font-size: 15px;
}
.limit-form {
  margin-top: 24px;
  max-width: 600px;
}
.el-form-item {
  margin-bottom: 18px;
}
.tip-row {
  margin-bottom: 18px;
  margin-left: 100px;
}
.tip-text {
  color: #909399;
  font-size: 13px;
}
.el-button {
  min-width: 100px;
}
.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}
.section-title-left {
  flex: 1;
}
.section-title-right {
  flex-shrink: 0;
  margin-top: 8px;
}
</style>
